package com.android.DSViews;

import static com.android.DSViews.Vertex.X;
import static com.android.DSViews.Vertex.Y;
import static com.android.DSViews.Vertex.Z;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class ObjReader {
	
	public ObjReader()
	{
	}

	public final int BUFFER_SIZE = 8192;
	
	List<Vertex> readMesh(InputStream is) throws IOException 
	{
		List<Vertex> vertices = new ArrayList<Vertex>();				
		Reader r = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(r, BUFFER_SIZE);
		String line = null;
		int linenumber = 0;
		
		while ((line = br.readLine()) != null)
		{
			if(line.endsWith("\\"))
			{
				line = line.substring(0,line.length()-1);
				line += br.readLine();
			}
			linenumber++;
			line = line.trim();
			if(line.length()==0)
				continue;
			if (line.startsWith("#") || line.startsWith("o")
					|| line.startsWith("s") || line.startsWith("g")
					|| line.startsWith("mtllib")
					|| line.startsWith("usemtl") || line.startsWith("vt")) {
				continue;
			}
			
			if (line.startsWith("v")) {
				StringTokenizer tok = new StringTokenizer(line);
				tok.nextToken();
				Vertex v = new Vertex();
				v.vertex[X] = Float.parseFloat(tok.nextToken());
				v.vertex[Y] = Float.parseFloat(tok.nextToken());
				if (tok.hasMoreTokens()) {
					v.vertex[Z] = Float.parseFloat(tok.nextToken());
				}
				vertices.add(v);
				continue;
			}
			
		}
		
		return vertices;
	}
}
